package com.qubaopen.core.dao;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.impl.CriteriaImpl;
import org.hibernate.transform.ResultTransformer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import com.qubaopen.core.beans.Page;
import com.qubaopen.core.beans.PropertyFilter;
import com.qubaopen.core.beans.PropertyOrder;
import com.qubaopen.core.beans.PropertyFilter.MatchType;
import com.qubaopen.core.domain.DomainObject;
import com.qubaopen.core.utils.ReflectionUtils;

/**
 * 数据库访问层的泛型基类
 * 
 * @author ZhangYongYi
 * 
 * @version 1.0
 * 
 * @param <T>
 *            实现了DoomainObject接口的实体类
 * @param <PK>
 *            实体类主键类型
 */

@SuppressWarnings("unchecked")
public class GenericDao<T extends DomainObject, PK extends Serializable> {

	protected SessionFactory sessionFactory;

	private Class<T> type;

	public GenericDao(Class<T> type) {
		this.type = type;
	}

	/**
	 * 取得sessionFactory.
	 */
	public SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	/**
	 * 采用@Autowired按类型注入SessionFactory, 当有多个SesionFactory的时候在子类重载本函数.
	 */
	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * 取得当前Session.
	 */
	public Session getSession() {
		return sessionFactory.getCurrentSession();
	}

	/**
	 * 保存新增或修改的对象.
	 * 
	 * @param entity
	 *            实体对象
	 */

	public void saveOrUpdate(T entity) {
		Assert.notNull(entity, "entity不能为空");
		getSession().saveOrUpdate(entity);
	}

	public void save(T entity) {
		Assert.notNull(entity, "entity不能为空");
		getSession().save(entity);
	}

	public void update(T entity) {
		Assert.notNull(entity, "entity不能为空");
		getSession().update(entity);
	}

	/**
	 * 取得主键等于id的对象.
	 * 
	 * @param id
	 *            实体ID属性
	 * 
	 * @return
	 */

	public T get(PK id) {
		Assert.notNull(id, "id不能为空");
		return (T) getSession().get(type, id);
	}

	/**
	 * 按id删除对象.
	 * 
	 * @param id
	 *            实体ID属性值
	 */

	public void remove(PK id) {
		Assert.notNull(id, "id不能为空");
		remove(get(id));
	}

	/**
	 * 删除对象.
	 * 
	 * @param entity
	 *            对象必须是session中的对象或含id属性的transient对象.
	 */
	public void remove(T entity) {
		Assert.notNull(entity, "entity不能为空");
		getSession().delete(entity);
	}

	/**
	 * 获取全部对象.
	 */
	public List<T> getAll() {
		return find();
	}

	/**
	 * 获取全部对象, 支持按属性排序序.
	 * 
	 * @param orderByProperty
	 *            排序属性名称
	 * @param isAsc
	 *            是否正序排序
	 * @return
	 */

	public List<T> getAll(String orderByProperty, boolean isAsc) {
		Criteria c = createCriteria();
		if (isAsc) {
			c.addOrder(Order.asc(orderByProperty));
		} else {
			c.addOrder(Order.desc(orderByProperty));
		}
		return c.list();
	}

	/**
	 * 
	 * 按属性查找对象列表,匹配方式为相等.
	 * 
	 * @param propertyName
	 *            实体属性名称
	 * @param propertyValue
	 *            实体属性值
	 * @return
	 */

	public List<T> findBy(String propertyName, Object propertyValue) {
		Assert.hasText(propertyName, "propertyName不能为空");
		Criterion criterion = Restrictions.eq(propertyName, propertyValue);
		return find(criterion);
	}

	/**
	 * 按属性查找唯一对象,匹配方式为相等.
	 * 
	 * @param propertyName
	 *            实体属性名称
	 * @param propertyValue
	 *            实体属性值
	 * @return
	 */

	public T findUniqueBy(String propertyName, Object propertyValue) {
		Assert.hasText(propertyName, "propertyName不能为空");
		Criterion criterion = Restrictions.eq(propertyName, propertyValue);
		return (T) createCriteria(criterion).uniqueResult();
	}

	/**
	 * * 按HQL查询对象列表.
	 * 
	 * @param hql
	 *            HQL查询语句
	 * @param values
	 *            数量可变的参数,按顺序绑定.
	 * 
	 * @return
	 */

	public List<T> findByHql(String hql, Object... values) {
		return createQuery(hql, values).list();
	}

	/**
	 * * 按HQL查询对象列表.
	 * 
	 * @param hql
	 *            HQL查询 语句
	 * @param values
	 *            命名参数,按名称绑定.
	 * 
	 * @return
	 */

	public List<T> findByHql(String hql, Map<String, ? extends Object> values) {
		return createQuery(hql, values).list();
	}

	/**
	 * 按Criteria查询对象列表.
	 * 
	 * @param criterions
	 *            数量可变的Criterion.
	 */
	public List<T> find(Criterion... criterions) {
		return createCriteria(criterions).list();
	}

	/**
	 * 按Criteria查询对象列表.
	 * 
	 * @param order
	 *            排序条件.
	 * 
	 * @param criterions
	 *            数量可变的Criterion.
	 */
	public List<T> find(PropertyOrder order, Criterion... criterions) {
		return createCriteria(order, criterions).list();
	}

	/**
	 * 执行HQL进行批量修改/删除操作.
	 * 
	 * @param hql
	 *            HQL语句
	 * @param values
	 *            数量可变的参数,按顺序绑定.
	 * @return
	 */

	public int batchExecute(final String hql, final Object... values) {
		return createQuery(hql, values).executeUpdate();
	}

	/**
	 * 执行HQL进行批量修改/删除操作.
	 * 
	 * @param hql
	 *            HQL语句
	 * @param values
	 *            数量可变的参数，按名称绑定
	 * @return
	 */

	public int batchExecute(final String hql,
			final Map<String, ? extends Object> values) {
		return createQuery(hql, values).executeUpdate();
	}

	/**
	 * 根据查询HQL与参数列表创建Query对象.
	 * 
	 * 本类封装的find()函数全部默认返回对象类型为T,当不为T时使用本函数.
	 * 
	 * @param values
	 *            数量可变的参数,按顺序绑定.
	 */
	public Query createQuery(final String hql, final Object... values) {
		Assert.hasText(hql, "queryString不能为空");
		Query query = getSession().createQuery(hql);
		query.setCacheable(true);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				query.setParameter(i, values[i]);
			}
		}
		return query;
	}

	/**
	 * 根据查询HQL与参数列表创建Query对象.
	 * 
	 * @param values
	 *            命名参数,按名称绑定.
	 */
	public Query createQuery(final String queryString,
			final Map<String, ? extends Object> values) {
		Assert.hasText(queryString, "queryString不能为空");
		Query query = getSession().createQuery(queryString);
		query.setCacheable(true);
		if (values != null) {
			query.setProperties(values);
		}
		return query;
	}

	/**
	 * 执行SQL进行批量修改/删除操作.
	 * 
	 * @param sql
	 *            SQL语句
	 * @param values
	 *            数量可变的参数，按名称绑定
	 * @return
	 */

	public int batchExecuteSql(final String sql,
			final Map<String, ? extends Object> values) {
		return createSqlQuery(sql, values).executeUpdate();
	}

	/**
	 * // * 执行SQL进行批量修改/删除操作.
	 * 
	 * @param sql
	 *            // * SQL语句
	 * @param values
	 *            数量可变的参数,按顺序绑定.
	 * @return
	 */

	public int batchExecuteSql(final String sql, final Object... values) {
		return createSqlQuery(sql, values).executeUpdate();
	}

	/**
	 * 根据查询SQL与参数列表创建SQLQuery对象.
	 * 
	 * 本类封装的find()函数全部默认返回对象类型为T,当不为T时使用本函数.
	 * 
	 * @param values
	 *            数量可变的参数,按顺序绑定.
	 */
	public SQLQuery createSqlQuery(final String sql, final Object... values) {
		Assert.hasText(sql, "queryString不能为空");
		SQLQuery query = getSession().createSQLQuery(sql);
		query.setCacheable(true);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				query.setParameter(i, values[i]);
			}
		}
		return query;
	}

	/**
	 * 根据查询SQL与参数列表创建SQLQuery对象.
	 * 
	 * @param values
	 *            命名参数,按名称绑定.
	 */
	public SQLQuery createSqlQuery(final String sql,
			final Map<String, ? extends Object> values) {
		Assert.hasText(sql, "queryString不能为空");
		SQLQuery query = getSession().createSQLQuery(sql);
		query.setCacheable(true);
		if (values != null) {
			query.setProperties(values);
		}
		return query;
	}

	/**
	 * 根据Criterion条件创建Criteria.
	 * 
	 * 本类封装的find()函数全部默认返回对象类型为T,当不为T时使用本函数.
	 * 
	 * @param criterions
	 *            数量可变的Criterion.
	 */
	public Criteria createCriteria(final Criterion... criterions) {
		Criteria criteria = getSession().createCriteria(type);
		criteria.setCacheable(true);
		for (Criterion c : criterions) {
			if (c != null) {
				criteria.add(c);
			}
		}
		return criteria;
	}

	/**
	 * 根据Criterion条件创建Criteria.
	 * 
	 * 本类封装的find()函数全部默认返回对象类型为T,当不为T时使用本函数.
	 * 
	 * @param criterions
	 *            数量可变的Criterion.
	 */
	public Criteria createCriteria(PropertyOrder order,
			final Criterion... criterions) {
		Criteria criteria = getSession().createCriteria(type);
		criteria.setCacheable(true);
		for (Criterion c : criterions) {
			criteria.add(c);
		}

		if (order != null) {
			String[] orderByArray = StringUtils.split(order.getOrderBy(), ',');
			String[] orderArray = StringUtils.split(order.getOrderDir(), ',');

			Assert.isTrue(orderByArray.length == orderArray.length,
					"列表多重排序参数中,排序字段与排序方向的个数不相等");

			for (int i = 0; i < orderByArray.length; i++) {
				if (PropertyOrder.ASC.equalsIgnoreCase(orderArray[i])) {
					criteria.addOrder(Order.asc(orderByArray[i]));
				} else {
					criteria.addOrder(Order.desc(orderByArray[i]));
				}
			}
		}

		return criteria;
	}

	/**
	 * Flush当前Session.
	 */
	public void flush() {
		getSession().flush();
	}

	/**
	 * 执行count查询获得本次Hql查询所能获得的对象总数.
	 * 
	 * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
	 * 
	 * @param hql
	 *            HQL查询语句
	 * @param values
	 *            数量可变的参数类别，按顺序绑定
	 * @return
	 */

	protected long countHqlResult(final String hql, final Object... values) {
		long count = 0;
		String countHql = prepareCountHql(hql);

		try {
			count = findUnique(countHql, values);
		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:"
					+ countHql, e);
		}

		return count;
	}

	/**
	 * 执行count查询获得本次Hql查询所能获得的对象总数.
	 * 
	 * 本函数只能自动处理简单的hql语句,复杂的hql查询请另行编写count语句查询.
	 * 
	 * @param hql
	 *            HQL查询语句
	 * @param values
	 *            命名参数，按名称绑定
	 * @return
	 */

	protected long countHqlResult(final String hql,
			final Map<String, ? extends Object> values) {
		long count = 0;
		String countHql = prepareCountHql(hql);

		try {
			count = findUnique(countHql, values);

		} catch (Exception e) {
			throw new RuntimeException("hql can't be auto count, hql is:"
					+ countHql, e);
		}

		return count;
	}

	private String prepareCountHql(String orgHql) {
		String fromHql = orgHql;
		// select子句与order by子句会影响count查询,进行简单的排除.
		fromHql = "from " + StringUtils.substringAfter(fromHql, "from");
		fromHql = StringUtils.substringBefore(fromHql, "order by");

		String countHql = "select count(*) " + fromHql;
		return countHql;
	}

	/**
	 * 按HQL查询对象列表.
	 * 
	 * @param values
	 *            数量可变的参数,按顺序绑定.
	 */
	public <X> List<X> find(final String hql, final Object... values) {
		return createQuery(hql, values).list();
	}

	/**
	 * 按HQL查询对象列表.
	 * 
	 * @param values
	 *            命名参数,按名称绑定.
	 */
	public <X> List<X> find(final String hql,
			final Map<String, ? extends Object> values) {
		return createQuery(hql, values).list();
	}

	/**
	 * 按HQL查询唯一对象.
	 * 
	 * @param values
	 *            数量可变的参数,按顺序绑定.
	 */
	public <X> X findUnique(final String hql, final Object... values) {
		return (X) createQuery(hql, values).uniqueResult();
	}

	/**
	 * 按HQL查询唯一对象.
	 * 
	 * @param values
	 *            命名参数,按名称绑定.
	 */
	public <X> X findUnique(final String hql,
			final Map<String, ? extends Object> values) {
		return (X) createQuery(hql, values).uniqueResult();
	}

	/**
	 * 分页查询
	 * 
	 * @param page
	 *            分页参数
	 * @return
	 */

	public Page<T> getAll(final Page<T> page) {
		return findPage(page);
	}

	/**
	 * 按HQL分页查询.
	 * 
	 * @param page
	 *            分页参数. 注意不支持其中的orderBy参数.
	 * @param hql
	 *            hql语句.
	 * @param values
	 *            数量可变的查询参数,按顺序绑定.
	 * 
	 * @return 分页查询结果, 附带结果列表及所有查询输入参数.
	 */

	public Page<T> findPage(final Page<T> page, final String hql,
			final Object... values) {
		Assert.notNull(page, "page不能为空");

		Query q = createQuery(hql, values);

		if (page.isAutoCount()) {
			long totalCount = countHqlResult(hql, values);
			page.setTotalCount(totalCount);
		}

		setPageParameterToQuery(q, page);

		List<T> result = q.list();
		page.setResult(result);
		return page;
	}

	/**
	 * 按HQL分页查询.
	 * 
	 * @param page
	 *            分页参数. 注意不支持其中的orderBy参数.
	 * @param hql
	 *            hql语句.
	 * @param values
	 *            命名参数,按名称绑定.
	 * 
	 * @return 分页查询结果, 附带结果列表及所有查询输入参数.
	 */

	public Page<T> findPage(final Page<T> page, final String hql,
			final Map<String, ? extends Object> values) {
		Assert.notNull(page, "page不能为空");

		Query q = createQuery(hql, values);

		if (page.isAutoCount()) {
			long totalCount = countHqlResult(hql, values);
			page.setTotalCount(totalCount);
		}

		setPageParameterToQuery(q, page);

		List<T> result = q.list();
		page.setResult(result);
		return page;
	}

	/**
	 * 按Criteria分页查询.
	 * 
	 * @param page
	 *            分页参数.
	 * @param criterions
	 *            数量可变的Criterion.
	 * 
	 * @return 分页查询结果.附带结果列表及所有查询输入参数.
	 */
	public Page<T> findPage(final Page<T> page, final Criterion... criterions) {
		Assert.notNull(page, "page不能为空");

		Criteria c = createCriteria(criterions);

		if (page.isAutoCount()) {
			long totalCount = countCriteriaResult(c);
			page.setTotalCount(totalCount);
		}

		setPageParameterToCriteria(c, page);

		List<T> result = c.list();
		page.setResult(result);
		return page;
	}

	/**
	 * 设置分页参数到Query对象,辅助函数.
	 * 
	 * @param q
	 *            Query查询对象
	 * @param page
	 *            分页参数
	 * @return
	 */

	protected Query setPageParameterToQuery(final Query q, final Page<T> page) {

		Assert.isTrue(page.getPageSize() > 0, "Page Size must larger than zero");

		// hibernate的firstResult的序号从0开始
		q.setFirstResult(page.getStart());
		q.setMaxResults(page.getPageSize());
		return q;
	}

	/**
	 * 
	 * 设置分页参数到Criteria对象,辅助函数.
	 * 
	 * @param c
	 *            Criteria查询对象
	 * @param page
	 *            分页参数
	 * @return
	 */

	protected Criteria setPageParameterToCriteria(final Criteria c,
			final Page<T> page) {
		// hibernate的firstResult的序号从0开始
		c.setFirstResult(page.getStart());
		c.setMaxResults(page.getPageSize());

		if (page.isOrderBySetted()) {
			String[] orderByArray = StringUtils.split(page.getOrderBy(), ',');
			String[] orderArray = StringUtils.split(page.getOrderDir(), ',');

			Assert.isTrue(orderByArray.length == orderArray.length,
					"分页多重排序参数中,排序字段与排序方向的个数不相等");

			for (int i = 0; i < orderByArray.length; i++) {
				if (Page.ASC.equalsIgnoreCase(orderArray[i])) {
					c.addOrder(Order.asc(orderByArray[i]));
				} else {
					c.addOrder(Order.desc(orderByArray[i]));
				}
			}
		}
		return c;
	}

	/**
	 * * 执行count查询获得本次Criteria查询所能获得的对象总数.
	 * 
	 * @param c
	 *            Criteria查询对象
	 * @return
	 */

	protected long countCriteriaResult(final Criteria c) {
		CriteriaImpl impl = (CriteriaImpl) c;

		// 先把Projection、ResultTransformer、OrderBy取出来,清空三者后再执行Count操作
		Projection projection = impl.getProjection();
		ResultTransformer transformer = impl.getResultTransformer();

		List<CriteriaImpl.OrderEntry> orderEntries = null;
		try {
			orderEntries = (List<CriteriaImpl.OrderEntry>) ReflectionUtils
					.getFieldValue(impl, "orderEntries");
			ReflectionUtils.setFieldValue(impl, "orderEntries",
					new ArrayList<Object>());
		} catch (Exception e) {

		}

		// 执行Count查询
		Long totalCount = (Long) c.setProjection(Projections.rowCount())
				.uniqueResult();

		// 将之前的Projection,ResultTransformer和OrderBy条件重新设回去
		c.setProjection(projection);

		if (projection == null) {
			c.setResultTransformer(CriteriaSpecification.ROOT_ENTITY);
		}
		if (transformer != null) {
			c.setResultTransformer(transformer);
		}
		try {
			ReflectionUtils.setFieldValue(impl, "orderEntries", orderEntries);
		} catch (Exception e) {

		}

		return totalCount;
	}

	/**
	 * * 按属性查找对象列表,支持多种匹配方式.
	 * 
	 * 
	 * @param propertyName
	 *            属性条件名称
	 * @param value
	 *            属性条件值
	 * @param matchType
	 *            匹配方式,目前支持的取值见PropertyFilter的MatcheType enum.
	 * @return
	 */

	public List<T> findBy(final String propertyName, final Object value,
			final MatchType matchType) {
		Criterion criterion = buildPropertyFilterCriterion(propertyName, value,
				matchType);
		return find(criterion);
	}

	/**
	 * * 按属性过滤条件列表查找对象列表.
	 * 
	 * @param filters
	 *            属性过滤条件列表
	 * @return
	 */

	public List<T> getAll(List<PropertyFilter> filters) {
		Criterion[] criterions = buildPropertyFilterCriterions(filters);
		return find(criterions);
	}

	/**
	 * * 按属性过滤条件列表查找对象列表.
	 * 
	 * @param filters
	 *            属性过滤条件列表
	 * 
	 * @param order
	 *            属性排序条件
	 * @return
	 */

	public List<T> getAll(List<PropertyFilter> filters, PropertyOrder order) {
		Criterion[] criterions = buildPropertyFilterCriterions(filters);
		return find(order, criterions);
	}

	/**
	 * * 按属性过滤条件列表分页查找对象.
	 * 
	 * @param page
	 *            分页参数
	 * @param filters
	 *            属性过滤条件列表
	 * @return
	 */

	public Page<T> findPage(final Page<T> page,
			final List<PropertyFilter> filters) {
		Criterion[] criterions = buildPropertyFilterCriterions(filters);
		return findPage(page, criterions);
	}

	/**
	 * * 按属性条件列表创建Criterion数组,辅助函数.
	 * 
	 * @param filters
	 *            属性过滤条件列表
	 * @return
	 */

	protected Criterion[] buildPropertyFilterCriterions(
			final List<PropertyFilter> filters) {
		List<Criterion> criterionList = new ArrayList<Criterion>();
		for (PropertyFilter filter : filters) {
			String propertyName = filter.getPropertyName();

			boolean multiProperty = StringUtils.contains(propertyName,
					PropertyFilter.OR_SEPARATOR);
			if (!multiProperty) {

				// properNameName中只有一个属性的情况.
				Criterion criterion = buildPropertyFilterCriterion(
						propertyName, filter.getValue(), filter.getMatchType());
				criterionList.add(criterion);
			} else {

				// properName中包含多个属性的情况,进行or处理.
				Disjunction disjunction = Restrictions.disjunction();
				String[] params = StringUtils.split(propertyName,
						PropertyFilter.OR_SEPARATOR);

				for (String param : params) {
					Criterion criterion = buildPropertyFilterCriterion(param,
							filter.getValue(), filter.getMatchType());
					disjunction.add(criterion);
				}
				criterionList.add(disjunction);
			}
		}
		return criterionList.toArray(new Criterion[criterionList.size()]);
	}

	/**
	 * * 按属性条件参数创建Criterion,辅助函数.
	 * 
	 * @param propertyName
	 *            属性条件名称
	 * @param value
	 *            属性条件值
	 * @param matchType
	 *            匹配方式
	 * @return
	 */

	protected Criterion buildPropertyFilterCriterion(final String propertyName,
			final Object value, final MatchType matchType) {
		Assert.hasText(propertyName, "propertyName不能为空");
		Criterion criterion = null;

		if (MatchType.EQ.equals(matchType)) {
			criterion = Restrictions.eq(propertyName, value);
		}

		if (MatchType.NE.equals(matchType)) {
			criterion = Restrictions.ne(propertyName, value);
		}

		if (MatchType.GT.equals(matchType)) {
			criterion = Restrictions.gt(propertyName, value);
		}

		if (MatchType.GE.equals(matchType)) {
			criterion = Restrictions.ge(propertyName, value);
		}

		if (MatchType.LT.equals(matchType)) {
			criterion = Restrictions.lt(propertyName, value);
		}

		if (MatchType.LE.equals(matchType)) {
			criterion = Restrictions.le(propertyName, value);
		}

		if (MatchType.ISNULL.equals(matchType)) {
			criterion = Restrictions.isNull(propertyName);
		}

		if (MatchType.ISNOTNULL.equals(matchType)) {
			criterion = Restrictions.isNotNull(propertyName);
		}

		if (MatchType.LIKE.equals(matchType)) {
			criterion = Restrictions.ilike(propertyName, (String) value,
					MatchMode.ANYWHERE);
		}

		if (MatchType.START_LIKE.equals(matchType)) {
			criterion = Restrictions.ilike(propertyName, (String) value,
					MatchMode.START);
		}

		if (MatchType.END_LIKE.equals(matchType)) {
			criterion = Restrictions.ilike(propertyName, (String) value,
					MatchMode.END);
		}

		if (MatchType.IN.equals(matchType)) {
			criterion = Restrictions.in(propertyName, (Collection<?>) value);
		}

		return criterion;
	}

	/**
	 * 获取数据库服务器的当前时间,目前该方法在mysql数据库下测试通过
	 */
	public Date getDatabaseCurrentDateTime() {
		Date date = new Date();

		try {
			Object result = this.getSession()
					.createSQLQuery("select getdate()").uniqueResult();
			if (result != null) {
				date = (Date) result;
			}

		} catch (Exception e) {
			e.printStackTrace();
		}

		return date;
	}

}
